package com.woniuxy.configuration;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import com.woniuxy.realm.CustomRealm;


@Configuration
public class ShiroConfiguration {
	
	@Bean
	public CustomRealm realm() {
		//开启缓存
		CustomRealm realm = new CustomRealm();
		//认证缓存
		realm.setCachingEnabled(true);
		//开启认证缓存
		realm.setAuthenticationCachingEnabled(true);;
		realm.setAuthenticationCacheName("abc");
		//开启授权缓存
		realm.setAuthorizationCachingEnabled(true);
		realm.setAuthorizationCacheName("cba");
		return realm;
	}
	
	@Bean
	public SecurityManager securityManager(CustomRealm realm) {
		DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
		manager.setRealm(realm);
		manager.setCacheManager(ehCacheManager());
		return manager;
	}
	
	@Bean
	public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
		ShiroFilterFactoryBean factorybean = new ShiroFilterFactoryBean();
		factorybean.setSecurityManager(securityManager);
		factorybean.setLoginUrl("/login.html");
		factorybean.setUnauthorizedUrl("/error.html");
		//设置过滤器链
		Map<String,String> map = new LinkedHashMap<>();
		map.put("/login.html", "anon");
		map.put("/user/login", "anon");
		map.put("/css/**","anon");
		map.put("/js/**","anon");
		map.put("/image/**","anon");
		map.put("/layer/**","anon");
		map.put("/logout", "logout");
		map.put("/**", "authc");
		factorybean.setFilterChainDefinitionMap(map);
		return factorybean;
	}
	
	
	/**
	 * 配置生命周期管理器
	 */
	@Bean
	public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
		return new LifecycleBeanPostProcessor();
	}
	
	@Bean
	@DependsOn("lifecycleBeanPostProcessor")
	public DefaultAdvisorAutoProxyCreator daapc() {
		DefaultAdvisorAutoProxyCreator creater = new DefaultAdvisorAutoProxyCreator();
		creater.setProxyTargetClass(true);
		return creater;
	}
	
	@Bean
	public AuthorizationAttributeSourceAdvisor advisor(SecurityManager securityManager) {
		AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
		advisor.setSecurityManager(securityManager);
		return advisor;
	}
	
	@Bean
	public EhCacheManager ehCacheManager() {
		EhCacheManager manager = new EhCacheManager();
		manager.setCacheManagerConfigFile("classpath:ehcache.xml");
		return manager;
	}
}
